package actions;

import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.Set;

import parameters.RLM_Parameters;

import client.ClientApplication;
import client.ClientBindObject;
import client.ClientSocketConnection;
import client_gui.ClientWindow;

public class LogoutAction extends RLMAbstractAction {


	public LogoutAction(ClientWindow owner) {
		setActionOwner(owner);
//		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
		putValue(SMALL_ICON, loadIcon("images/logout.png"));
		putValue(NAME, "Logout");
		putValue(SHORT_DESCRIPTION, "Logout");
		
		setActionItem();
	}
	

	
	public void actionPerformed(ActionEvent e) {
		
		ClientSocketConnection connection = getActionOwner().getApplicaton().retrieveSocketConnection();
		
		String logoutCommand = "LOGOUT " + getActionOwner().getApplicaton().getClientUser().getUsername();

		connection.setMessage(LOGOUT_CMD, logoutCommand);
		
//		String response = connection.buffers[LOGOUT_CMD].read();
		
//		if (response.startsWith("100")) {
			getActionOwner().setTrayIcon(OFFLINE_STATUS);
			getActionOwner().getApplicaton().setState(INITIAL_STATE);
			
			Set<String> keys = ClientApplication.clientBinding.keySet();
			
			Iterator<String> keysIterator = keys.iterator();
			
			while ( keysIterator.hasNext() ) {
				String key = keysIterator.next();
				
				ClientBindObject cbo = ClientApplication.clientBinding.get(key);
				if (cbo.getDialog() != null) {
					cbo.getDialog().setConnection(null);
					cbo.getDialog().dispose();
				}
				if (cbo.getConnection() != null) {
					cbo.getConnection().quitConnection();
				}
				if ( cbo.getCall() != null ) {
					cbo.getCall().setAudioEstablished(false);
					cbo.getCall().setVideoEstablished(false);
				}
				cbo.setConnection(null);
			}
			
			ClientApplication.clientBinding.clear();
			
			getActionOwner().getApplicaton().getClientModel().clearModel();
			
			getActionOwner().refreshWindow();
			
			connection.quitConnection();
			getActionOwner().getApplicaton().setSocketConnection(null);
			connection = null;
			
					
			getActionOwner().getApplicaton().stopClientServer();

			try {
				ClientApplication.clientServerSemaphore.acquire();
			}
			catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			
			getActionOwner().getApplicaton().writeInputParameters();
			RLM_Parameters.storeParameters();
			
			ClientApplication.multicastReceived = false;
//		}
		
	}
	
}
